'''
Desc: 通过接入号查询宽带账号或者其他的业务账号
Author: 马大胖
Mail: mazhenjun.lk.xx@gmail.com
Date: 2024-08-16 16:21:21
'''


import tkinter as tk
from tkinter import scrolledtext
from tkinter.messagebox import *
import requests
import logging
from selenium import webdriver


# 根据 接入号 查询新一代施工调度中的待办箱列表
find_todo_box_url = "http://136.64.71.234:30121/aiops/api/v1/flow/tj/constructionWorkTable/getGzConstructionInfo"
# 根据 flowId 查询接入号对应的 formId 和 pId
find_formIdAndPid_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFlowForm"
# 根据 formId 和 pId 查询业务列表
find_broadband_info_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFormData"

# 设置全局代理代理
proxies = {
    "http": "http://136.64.71.234:30121",
    "https": "http://136.64.71.234:30121"
}

# Base payload
base_payload = {
    "accessNo": "",
    "type": "B",
    "page": 0,
    "pageSize": 12
}



# 最终的数据vo对象
final_result = {}

# 定义一个变量序号
index = 1
log = ""
result = ""

def step_one_get_base_data(access_code, headers):
    payload = base_payload.copy()
    payload['accessNo'] = access_code

    try:
        response = requests.post(find_todo_box_url, headers=headers, json=payload, proxies=proxies)

        if response.status_code == 200:
            logging.info(f"成功获取 接入号: {access_code} 的基础数据")
            return response.json()
        else:
            logging.error(f"获取 接入号: {access_code} 的基础数据失败, 状态码: {response.status_code}, 响应内容: {response.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None

def extract_ids_with_product_type(response):
    address_url_accessNo_list = []
    if response and "content" in response:
        for key in response.get("content", []):
            result_param = {
                "flow_id": key.get("flow_id"),
                "access_no": key.get("access_no"),
                "address": key.get("address"),
                "url": key.get("url")
            }
            log = f"{index}."
            address_url_accessNo_list.append(result_param)
            final_result[key.get("access_no")] = result_param
    return address_url_accessNo_list

def getFormIdAndPid(step_one_result, headers):
    result = []
    for step_two in step_one_result:
        params = {'flowId': step_two.get("flow_id")}
        try:
            response = requests.get(find_formIdAndPid_url, headers=headers, params=params, proxies=proxies)

            if response.status_code == 200:
                logging.info(f"成功获取 接入号: {step_two.get('access_no')} 的 Form-Pid 数据")
                result.append(response.json())
            else:
                logging.error(f"获取 接入号: {step_two.get('access_no')} 的 Form-Pid 数据失败, 状态码: {response.status_code}, 响应内容: {response.text}")
                return None
        except requests.RequestException as e:
            logging.error(f"请求失败: {e}")
    return result

def getBroadbandData(final_result, headers):
    result = []
    for step_three in final_result:
        temp = final_result[step_three]
        params = {'formId': temp.get("formId"), "pId": temp.get("pId"), "pageNum": 0, "pageSize": 5}
        try:
            response = requests.get(find_broadband_info_url, headers=headers, params=params, proxies=proxies)

            if response.status_code == 200:
                logging.info(f"成功获取 接入号: {temp.get('access_no')} 的宽带详情数据")
                result.append(response.json())
            else:
                logging.error(f"获取 接入号: {temp.get('access_no')} 的宽带详情数据失败")
        except requests.RequestException as e:
            logging.error(f"请求失败: {e}")
    return result

def remove_duplicates(arr):
    return list(set(arr))


# 获取 Cookie
def getCookie():
    print(12312)
    response = requests.get("http://136.64.71.234:30121/aiops/app/baseTj/homePage/#/modalComplaint?menuId=10000000000799&serverUrl=%252Faiops%252Fapp%252FbaseTj%252FhomePage%252F%2523%252FworktableTodoBoxGz")
    # 获取服务器返回的Cookie
    cookies = response.cookies

    # 打印Cookie
    for cookie in cookies:
        print(f"Name: {cookie.name}, Value: {cookie.value}")
    # 设置 WebDriver，例如 ChromeDriver
    #driver = webdriver.Chrome()  # 确保你已经将 chromedriver 放在系统 PATH 中

    # 打开目标网站
    #driver.get('https://www.52pojie.cn/')

    # 登录操作等

    # 获取所有 cookies
    #cookies = driver.get_cookies()

    # 打印所有 cookies
    #for cookie in cookies:
        #print(cookie)


    # 关闭浏览器
    #driver.quit()

    # cookie_text.insert(tk.END, "asjkdajskdanskdnaskdnaskdnas")

    # if (random.randint(0, 1) == 0):
    #     print(showinfo(title="获取Cookie", message="获取成功"))
    # else:
    #     print(showerror(title="获取Cookie", message="获取失败,请手动到浏览器复制Cookie"))
    


# GUI部分
def submit():
    log_text.config(state="normal")  # 使日志区域可写
    output1 = f"查询接入号: QWWF123456 成功\n"
    log_text.insert(tk.END, output1)  # 插入日志信息
    log_text.config(state="disabled")  # 禁止用户编辑

    output2 = f"02222222222\n"
    result_text.insert(tk.END, output2)
    access_codes = access_number_text.get("1.0", tk.END).strip().split(',')
    cookie = cookie_text.get("1.0", tk.END).strip()

    headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "Cookie": cookie
    }

    # 修改为一个账号从头至尾查询
    for access_code in access_codes:
        response = step_one_get_base_data(access_code.strip(), headers)
        if response:
            step_one_result = extract_ids_with_product_type(response)
            step_two_result = getFormIdAndPid(step_one_result, headers)

            if step_two_result:
                for result_temp in step_two_result:
                    formId = ""
                    access_no = ""
                    pId = ""
                    for table in result_temp.get("table", {}):
                        for t_tmp in table.get("field", {}):
                            if t_tmp.get("fieldName") == "REQUEST_ID":
                                pId = t_tmp.get("value")
                            if t_tmp.get("fieldName") == "access_no":
                                access_no = t_tmp.get("value")
                            if t_tmp.get("fieldName") == "product_list_tab":
                                a = t_tmp.get("value")
                                formId = a.get("formId")
                    b = final_result[access_no]
                    b["formId"] = formId
                    b["pId"] = pId

                fff = getBroadbandData(final_result, headers)
                if len(fff) > 0:
                    one = []
                    for result_temp in fff:
                        two = []
                        a = result_temp.get("data")
                        for a_temp in a:
                            two.append(a_temp.get("accessNo"))
                        one.append(two)

                    for a in one:
                        a_t = []
                        f_t = []
                        a_unique = remove_duplicates(a)
                        for bbb in a_unique:
                            ccc = final_result.get(bbb, None)
                            if ccc is not None:
                                a_t.append(a)
                                f_t.append(ccc)
                        output = f"{next((f_t['address'] for f_t in f_t), 'Not found')}, {a_unique}\n"
                        result_text.insert(tk.END, output)

# 创建主窗口
root = tk.Tk()
root.title("旭旭小仙女的工具箱")

# 调整窗口大小
root.geometry("800x600")  # 设置窗口的初始尺寸

# 接入号标签和文本域
access_number_label = tk.Label(root, text="接入号(用逗号分隔):")
access_number_label.place(x=10, y=10)

access_number_text = tk.Text(root, height=5, width=50)
access_number_text.place(x=150, y=10, width=600, height=100)

# Cookie标签和文本域
cookie_label = tk.Label(root, text="Cookie:")
cookie_label.place(x=10, y=120)

cookie_text = tk.Text(root, height=5, width=50)
cookie_text.place(x=150, y=120, width=600, height=100)

# 获取Cookie按钮
getCookie_button = tk.Button(root, text="获取Cookie", command=getCookie, state="disabled")
getCookie_button.place(x=150, y=230, width=300, height=30)

# 提交按钮
submit_button = tk.Button(root, text="提交", command=submit)
submit_button.place(x=460, y=230, width=300, height=30)

# 日志显示区域 (左侧，不可编辑，背景灰色)
log_label = tk.Label(root, text="日志:")
log_label.place(x=10, y=270)

log_text = scrolledtext.ScrolledText(root, height=20, state="disabled", bg="lightgray", width=30)
log_text.place(x=10, y=300, width=290, height=250)

# 结果显示区域 (右侧，可编辑)
result_label = tk.Label(root, text="结果:")
result_label.place(x=170, y=270)

result_text = scrolledtext.ScrolledText(root, height=20)
result_text.place(x=310, y=300, width=490, height=250)

# 启动主循环
root.mainloop()